# coding=utf-8
"""
Copyright 2019-2020 Fang Jin Biao

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

# @Time    : 2020/7/19 19:16
# @Author  : Fang Jin Biao
# @Email   : 215466914@qq.com
# @File    : devops_service.py
# @Project : SnowAdminWeb
import datetime
import uuid
from collections import OrderedDict

from sqlalchemy import or_

from webapp.config import api_utils
from webapp.dto_mapper import paper_help_fields, app_fields, deploy_fields, deployhistory_fields, database_fields
from webapp.extensions import AppException
from webapp.models import PaperHelp,db
from webapp.tools import format_date, download_excel, connect_server
from flask_restful import marshal

class PaperHelpService:
    @staticmethod
    def query_all(page=1, size=9999, user_id:str=None, **kwargs) -> list:
        if user_id is None:
            raise AppException(f'查询的数据不存在!')
        id = kwargs.get('id')
        doi = kwargs.get('doi')
        task_status = kwargs.get('task_status')
        create_times = kwargs.get('createTime')
        sorts = kwargs.get('sort')
        if sorts:
           sort_params = api_utils.build_sorts(sorts, paper_help_fields, PaperHelp)
        else:
           sort_params = [PaperHelp.create_time.desc()]
        query = []
        if user_id:
            query.append(PaperHelp.user_id == user_id)
        if id:
            query.append(PaperHelp.id == id)
        if doi:
            query.append((PaperHelp.doi == doi))
        if task_status:
            query.append((PaperHelp.task_status == task_status))
        if create_times and len(create_times) >= 2:
            query.append((PaperHelp.create_time.between(create_times[0], create_times[1])))
        return PaperHelp.query.filter(*query).order_by(*sort_params).paginate(int(page), per_page=int(size),
                                                                              error_out=False)
    def query_search_key(page=1, size=9999,  **kwargs) -> list:
        id = kwargs.get('id')
        print("#print(id)print(id)print(id)")
        print(id)
        return PaperHelp.query.filter(PaperHelp.id == id).paginate(int(page), per_page=int(size),
                                                                              error_out=False)
    @staticmethod
    def create(curr_data: PaperHelp):
        curr_data.create_time = datetime.datetime.now()
        db.session.add(curr_data)
        db.session.flush()
        db.session.commit()
        paper_help_dict = marshal(curr_data, paper_help_fields)
        return paper_help_dict

    @staticmethod
    def update(curr_data: PaperHelp):
        old_data = PaperHelp.query.filter(PaperHelp.id == curr_data.id).one_or_none()
        if old_data is None:
            raise AppException(f'修改的数据可能已不存在!')
        old_data.id = curr_data.id
        if curr_data.user_id:
           old_data.user_id = curr_data.user_id
        old_data.doi = curr_data.doi
        old_data.task_type = curr_data.task_type
        old_data.task_status = curr_data.task_status
        old_data.task_id = curr_data.task_id
        old_data.result = curr_data.result
        old_data.is_read = curr_data.is_read

        db.session.commit()
        db.session.close()

    @staticmethod
    def delete(ids: list):
        if ids:
            old_list = db.session.query(PaperHelp).filter(PaperHelp.id.in_(ids)).all()
            for d in old_list:
                db.session.delete(d)
            db.session.commit()

    @staticmethod
    def find_by_id(id: int = None,user_id:str=None) -> PaperHelp:
        if user_id is None:
            raise AppException(f'您所操作的对象已不存在!')
        data = PaperHelp.query.filter(PaperHelp.id == id,PaperHelp.user_id == user_id).one_or_none()
        if data is None:
            raise AppException(f'您所操作的对象已不存在!')
        return data
